package com.mazaiting.classfile.attr.info;

import com.mazaiting.classfile.ClassReader;
import com.mazaiting.classfile.constant.ConstantPool;
import com.mazaiting.classfile.constant.info.ConstantFloatInfo;
import com.mazaiting.classfile.constant.info.ConstantInfo;
import com.mazaiting.classfile.constant.info.ConstantIntegerInfo;
import com.mazaiting.classfile.constant.info.ConstantLongInfo;
import lombok.Getter;

/**
 * 定长属性，只会出现在field_info结构中，用于 表示常量表达式的值
 *
 * @author mazaiting
 * @since 2021/8/12
 */
@Getter
public class ConstantValueAttribute extends AttributeInfo {
    /**
     * 常量索引 无符号 u2
     */
    private int constantValueIndex;

    public ConstantValueAttribute(ConstantPool pool, int index, int length) {
        super(pool, index, length);
    }

    @Override
    public void readInfo(ClassReader reader) {
        this.constantValueIndex = reader.readU2ToUnsignedShort();
    }

    /**
     * 获取常量值
     *
     * @return 常量
     */
    public Object getConstantValue() {
        ConstantInfo constantInfo = pool.getConstantInfo(constantValueIndex);
        if (constantInfo instanceof ConstantLongInfo) {
            return ((ConstantLongInfo) constantInfo).getValue();
        } else if (constantInfo instanceof ConstantIntegerInfo) {
            return ((ConstantIntegerInfo) constantInfo).getValue();
        } else if (constantInfo instanceof ConstantFloatInfo) {
            return ((ConstantFloatInfo) constantInfo).getValue();
        } else {
            return pool.getUtf8(constantValueIndex);
        }
    }

    @Override
    public String toString() {
        return "ConstantValueAttribute{" +
                "constantValueIndex=" + constantValueIndex +
                '}';
    }

}


















